package com.ErpCoreWeb.View;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.UI.CColumnDefaultValInView;
import com.ErpCoreModel.UI.CColumnDefaultValInViewDetail;
import com.ErpCoreModel.UI.CView;
import com.ErpCoreModel.UI.CViewDetail;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class SetDefaultVal
 */
@WebServlet("/SetDefaultVal")
public class SetDefaultVal extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

    public CView m_View = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SetDefaultVal() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
		try {
			String id = request.getParameter("id");
			if (Global.IsNullParameter(id)) {
				response.getWriter().close();
			}
			m_View = (CView) Global.GetCtx(this.getServletContext())
					.getViewMgr().Find(Util.GetUUID(id));
			if (m_View == null) {
				response.getWriter().close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
        	GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
        	PostData();
            return ;
        }
        else if (Action.equalsIgnoreCase("Cancel"))
        {
        	m_View.getColumnDefaultValInViewMgr().Cancel();
            return ;
        }
		
	}

    void GetData()
    {
        String table_id=request.getParameter("table_id");
        CTable table = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(Util.GetUUID(table_id));

        String sData = "";
        
        List<CBaseObject> lstObj = table.getColumnMgr().GetList();

        int iCount = 0;
        for (CBaseObject obj : lstObj)
        {
            CColumn col = (CColumn)obj;
            if (col.getCode().equalsIgnoreCase("id")
                || col.getCode().equalsIgnoreCase("Creator")
                || col.getCode().equalsIgnoreCase("Created")
                || col.getCode().equalsIgnoreCase("Updator")
                || col.getCode().equalsIgnoreCase("Updated"))
                continue;
            if (table.getId().equals( m_View.getFW_Table_id())) //主表
            {
                CColumnDefaultValInView cdviv = m_View.getColumnDefaultValInViewMgr().FindByColumn(col.getId());
                String DefaultVal = cdviv != null ? cdviv.getDefaultVal() : "";
                String ReadOnly = (cdviv != null && cdviv.getReadOnly()) ? "1" : "0";
                
                sData += String.format("{ \"id\": \"%s\",\"ColName\":\"%s\",\"DefaultVal\":\"%s\",\"ReadOnly\":\"%s\"},"
                    , col.getId().toString(), col.getName(), DefaultVal, ReadOnly);
            }
            else //从表
            {
                CViewDetail ViewDetail = m_View.getViewDetailMgr().FindByTable(table.getId());
                CColumnDefaultValInViewDetail cdvivd = ViewDetail.getColumnDefaultValInViewDetailMgr().FindByColumn(col.getId());
                String DefaultVal = cdvivd != null ? cdvivd.getDefaultVal() : "";
                String ReadOnly = (cdvivd != null && cdvivd.getReadOnly()) ? "1" : "0";

                sData += String.format("{ \"id\": \"%s\",\"ColName\":\"%s\",\"DefaultVal\":\"%s\",\"ReadOnly\":\"%s\"},"
                    , col.getId(), col.getName(), DefaultVal, ReadOnly );
            }
            iCount++;
        }

		if (sData.endsWith(","))
			sData = sData.substring(0, sData.length() - 1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, iCount);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void PostData()
    {
        String table_id=request.getParameter("table_id");
        CTable table = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(Util.GetUUID(table_id));

        String GridData = request.getParameter("GridData");

        if (table.getId().equals( m_View.getFW_Table_id())) //主表
        {
            String[] arr1 = GridData.split(";");
            for (int i = 0; i < arr1.length; i++)
            {
                String[] arr2 = arr1[i].split(":");
                UUID colid = Util.GetUUID(arr2[0]);

                if (arr2[1].trim().length()==0)
                {
                    m_View.getColumnDefaultValInViewMgr().RemoveByColumn(colid);
                }
                else
                {
                    CColumnDefaultValInView cdviv = m_View.getColumnDefaultValInViewMgr().FindByColumn(colid);
                    if (cdviv == null)
                    {
                        cdviv = new CColumnDefaultValInView();
                        cdviv.Ctx = Global.GetCtx(this.getServletContext());
                        cdviv.setFW_Table_id ( table.getId());
                        cdviv.setFW_Column_id ( colid);
                        cdviv.setDefaultVal ( arr2[1].trim());
                        cdviv.setReadOnly ( (!arr2[2].equals("1")) ? true : false);
                        cdviv.setUI_View_id ( m_View.getId());
                        m_View.getColumnDefaultValInViewMgr().AddNew(cdviv);
                    }
                    else
                    {
                        cdviv.setDefaultVal ( arr2[1].trim());
                        cdviv.setReadOnly ( (!arr2[2].equals("1")) ? true : false);
                        m_View.getColumnDefaultValInViewMgr().Update(cdviv);
                    }
                }
            }
        }
        else
        {
            CViewDetail ViewDetail = m_View.getViewDetailMgr().FindByTable(table.getId());
            
            String[] arr1 = GridData.split(";");
            for (int i = 0; i < arr1.length; i++)
            {
                String[] arr2 = arr1[i].split(":");
                UUID colid =  Util.GetUUID(arr2[0]);

                if (arr2[1].trim().length()==0)
                {
                    ViewDetail.getColumnDefaultValInViewDetailMgr().RemoveByColumn(colid);
                }
                else
                {
                    CColumnDefaultValInViewDetail cdvivd = ViewDetail.getColumnDefaultValInViewDetailMgr().FindByColumn(colid);
                    if (cdvivd == null)
                    {
                        cdvivd = new CColumnDefaultValInViewDetail();
                        cdvivd.Ctx = Global.GetCtx(this.getServletContext());
                        cdvivd.setFW_Table_id ( table.getId());
                        cdvivd.setFW_Column_id ( colid);
                        cdvivd.setDefaultVal ( arr2[1].trim());
                        cdvivd.setReadOnly ( (!arr2[2].equals("1")) ? true : false);
                        cdvivd.setUI_ViewDetail_id ( ViewDetail.getId());
                        ViewDetail.getColumnDefaultValInViewDetailMgr().AddNew(cdvivd);
                    }
                    else
                    {
                        cdvivd.setDefaultVal ( arr2[1].trim());
                        cdvivd.setReadOnly ( (!arr2[2] .equals("1")) ? true : false);
                        ViewDetail.getColumnDefaultValInViewDetailMgr().Update(cdvivd);
                    }
                }
            }
        }

    }
    
}
